package com.bnlr.lrparking.appui.carport.recommend;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bnlr.lrparking.appui.stall.StallBegRentBuy;
import com.bnlr.lrparking.appui.stall.StallDealDetailActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.model.ConditionBean;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.constant.Params;
import com.bnlr.lrparking.appui.carport.filtrate.FiltrateBean;
import com.bnlr.lrparking.appui.carport.filtrate.FiltrateConditionAdapter;
import com.bnlr.lrparking.appui.carport.filtrate.FiltrateConditionBean;
import com.bnlr.lrparking.view.ConditionPopup;
import com.bnlr.lrparking.widget.refresh.XRefreshLayout;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomJavaHttpListener;
import com.yolanda.nohttp.NoHttp;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * @author chenzhen
 * @date 2018/3/27
 * 推荐车位
 */

public class RecommendParkingActivity extends BaseActivity {

    @BindView(R.id.tv_nav_title)
    TextView tvNavTitle;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.x_refresh)
    XRefreshLayout xRefresh;
    @BindView(R.id.ll_hint)
    LinearLayout llHint;
    @BindView(R.id.tv_xq_name)
    TextView tvXqName;
    @BindView(R.id.ll_no_coincident)
    LinearLayout llNoCoincident;
    @BindView(R.id.iv_hint)
    ImageView ivHint;
    @BindView(R.id.tv_hint_tips)
    TextView tvHintTips;
    private Unbinder unbinder;
    private Map paramsMap = new HashMap();
    private RecommendStallAdapter adapter;
    private List<RecommendStallBean.ModelBean.ListBean> dataList = new ArrayList<>();
    private List<FiltrateConditionBean> filtrateData = new ArrayList<>();
    private FiltrateConditionAdapter filtrateAdapter;
    private int id;
    private Map<String,Integer> tagMap = new HashMap<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recommendparking);
        unbinder = ButterKnife.bind(this);
        tvNavTitle.setText("推荐车位");
        ivHint.setImageResource(R.mipmap.nodata);
        tvHintTips.setText("此小区暂无车位开放，敬请期待");
        Intent intent = getIntent();
        int tag = intent.getIntExtra("recommend_tag",0);
        if (tag != 0) {
            id =  Params.choose_community_id;
            tvXqName.setText(Params.choose_community_name);
        } else {
            id = intent.getIntExtra("select_recommend_id",0);
            String name = intent.getStringExtra("select_recommend_name");
            Params.choose_community_id = id;
            Params.choose_community_name = name;
            if (!TextUtils.isEmpty(name)) {
                tvXqName.setText(name);
            }
        }
        initView();
        getCondition();
        getRecommendStall();

    }



    private void initView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new RecommendStallAdapter(dataList);
        recyclerView.setAdapter(adapter);
        recyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent;
                if (dataList.get(position).getType() == 10 || dataList.get(position).getType() == 11) {
                    intent = new Intent(RecommendParkingActivity.this, StallDealDetailActivity.class);
                } else {
                    intent = new Intent(RecommendParkingActivity.this, StallBegRentBuy.class);
                }
                intent.putExtra("stall_id", dataList.get(position).getId());
                startActivity(intent);
            }
        });
    }

    /**
     * 获取筛选条件
     */
    private void getCondition() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.BASE_JAVA_URL+"system/getLimit", LrConstant.POST);
            mRequest.add("type",2);
            // 添加到请求队列+
            CallServer.getRequestInstance().add(this, mRequest,
                    new CustomJavaHttpListener<ConditionBean>(this, true, ConditionBean.class) {
                        @Override
                        public void doWork(ConditionBean data, int code) {
                            List<ConditionBean.ModelBean> modelBeans = data.getModel();
                            List<FiltrateConditionBean> list = new ArrayList<>();
                            for (int i = 0; i < modelBeans.size(); i++) {
                                list.add(new FiltrateConditionBean(true,modelBeans.get(i).getDesc()));
                                for (int j = 0; j < modelBeans.get(i).getData().size(); j++) {
                                    ConditionBean.ModelBean.DataBean cmd = modelBeans.get(i).getData().get(j);
                                    list.add(new FiltrateConditionBean(new FiltrateBean
                                            (modelBeans.get(i).getKey(),cmd.getValue(),cmd.getTxt(),false)));
                                }

                            }
                            filtrateData.clear();
                            filtrateData.addAll(list);
                            //filtrateAdapter.notifyDataSetChanged();

                        }

                        @Override
                        public void onFinally(String obj, int code, boolean isSucceed) throws JSONException {
                            super.onFinally(obj, code, isSucceed);

                        }
                    }, false);
        } catch (Exception e) {
        }
    }
    /**
     * 获取推荐车位列表
     */
    private void getRecommendStall() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.BASE_JAVA_URL + "system/advanceParking", LrConstant.POST);
            // 添加到请求队列+
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("parkingId", id);
            if (paramsMap != null && paramsMap.size() > 0) {
                for (Object key : paramsMap.keySet()
                        ) {
                    List<String> value = (List<String>) paramsMap.get(key);
                    String values = value.toString();
                    String result = values.replaceAll("\\[", "").replaceAll("]", "")
                            .replaceAll(" ", "");
                    Log.e("TTTTT",(String) key+"--"+result);
                    mRequest.add((String) key, result);
                }
            }
            Log.e("TTTTT",AppConfig.getInstance().getString("uid", "")+"--"+id);
            CallServer.getRequestInstance().add(this, mRequest,
                    new CustomJavaHttpListener<RecommendStallBean>(this, true, RecommendStallBean.class) {
                        @Override
                        public void doWork(RecommendStallBean data, int code) {
                            if (data.getModel() != null) {
                                if (data.getModel().getFlag() == 1) {
                                    //  有符合条件的
                                    llNoCoincident.setVisibility(View.GONE);
                                    llHint.setVisibility(View.GONE);
                                    if (data.getModel() != null && data.getModel().getList().size() > 0) {
                                        dataList.clear();
                                        dataList.addAll(data.getModel().getList());
                                        adapter.notifyDataSetChanged();
                                    }
                                } else if (data.getModel().getFlag() == 0) {
                                    //  无符合条件的
                                    if (data.getModel().getList() != null && data.getModel().getList().size() > 0){
                                        //  猜您需要
                                        llNoCoincident.setVisibility(View.VISIBLE);
                                        llHint.setVisibility(View.GONE);
                                    } else {
                                        //  无数据
                                        llNoCoincident.setVisibility(View.GONE);
                                        llHint.setVisibility(View.VISIBLE);
                                    }
                                    dataList.clear();
                                    dataList.addAll(data.getModel().getList());
                                    adapter.notifyDataSetChanged();
                                }
                            }

                        }

                        @Override
                        public void onFinally(String obj, int code, boolean isSucceed) throws JSONException {
                            super.onFinally(obj, code, isSucceed);

                        }
                    }, true);
        } catch (Exception e) {
        }

    }

    @Override
    protected void onDestroy() {
        if (unbinder != null) {
            unbinder.unbind();
        }
        super.onDestroy();
    }

    @OnClick({R.id.tv_sx,R.id.rely_select_xq,R.id.tv_change_condition})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_change_condition:
            case R.id.tv_sx:
                chooseCondition();
                break;
            case R.id.rely_select_xq:   // 选择小区
                startActivityForResult(new Intent(this,ChooseCommunityActivity.class)
                        .putExtra("is_from_park",true),1010);
                break;
            default:
                break;
        }
    }

    /**
     * 筛选条件
     */
    private void chooseCondition() {
        View view = View.inflate(RecommendParkingActivity.this,R.layout.recommend_stall_condition_layout,null);
        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.rv_condition);
        recyclerView.setLayoutManager(new GridLayoutManager(RecommendParkingActivity.this,3));
        final ConditionPopup popup = new ConditionPopup(RecommendParkingActivity.this,view);
        filtrateAdapter = new FiltrateConditionAdapter(filtrateData,tagMap);
        recyclerView.setAdapter(filtrateAdapter);
        popup.setTag();
        TextView sure = (TextView) view.findViewById(R.id.tv_condition_complete);
        ImageView ivBack = (ImageView) view.findViewById(R.id.iv_nav_back);
        popup.show();
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popup.hide();
                tagMap = filtrateAdapter.getMap();
                Map map = filtrateAdapter.getParams();
                if (map.size() > 0) {
                    paramsMap = map;
                } else {
                    paramsMap.clear();
                }
                getRecommendStall();
            }
        });
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tagMap = filtrateAdapter.getMap();
                getRecommendStall();
                popup.hide();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && requestCode == 1010) {
            id = data.getIntExtra("select_recommend_id",0);
            String name = data.getStringExtra("select_recommend_name");
            Params.choose_community_id = id;
            Params.choose_community_name = name;
            if (!TextUtils.isEmpty(name)) {
                tvXqName.setText(name);
            }
            tagMap.clear();
            if (filtrateAdapter != null) {
                for (int i = 0; i < filtrateData.size(); i++) {
                    if (!filtrateData.get(i).isHeader) {
                        filtrateData.get(i).t.setSelected(false);
                    }
                }
                filtrateAdapter.notifyDataSetChanged();
            }
            paramsMap.clear();

            getRecommendStall();
        }
    }
}
